package com.tarry.service.impl;

import com.google.common.base.Preconditions;
import com.tarry.bean.PageQuery;
import com.tarry.bean.PageResult;
import com.tarry.common.RequestHolder;
import com.tarry.dao.SysUserMapper;
import com.tarry.exception.ParamException;
import com.tarry.model.entity.SysUser;
import com.tarry.model.vo.UserVo;
import com.tarry.service.SysUserService;
import com.tarry.util.BeanValidator;
import com.tarry.util.IpUtil;
import com.tarry.util.MD5Util;
import com.tarry.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl extends BaseService<SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public void save(UserVo entity) {
        BeanValidator.check(entity);
        if (checkTelephoneExist(entity.getTelephone(), entity.getId())) {
            throw new ParamException("电话已被占用");
        }
        if (checkEmailExist(entity.getMail(), entity.getId())) {
            throw new ParamException("邮箱已被占用");
        }

        String password = PasswordUtil.randomPassword();
        //TODO:
        password = "12345678";
        String encryptedPassword = MD5Util.encrypt(password);
        SysUser user = SysUser.builder()
                .username(entity.getUsername())
                .telephone(entity.getTelephone())
                .mail(entity.getMail())
                .password(encryptedPassword)
                .deptId(entity.getDeptId())
                .status(entity.getStatus())
                .remark(entity.getRemark())
                .build();
        setOpratorInfo(user);
        // TODO: sendEmail

        sysUserMapper.insertSelective(user);
        //sysLogService.saveUserLog(null, user);
    }

    @Override
    public void update(UserVo entity) {

        BeanValidator.check(entity);
        if (checkTelephoneExist(entity.getTelephone(), entity.getId())) {
            throw new ParamException("电话已被占用");
        }
        if (checkEmailExist(entity.getMail(), entity.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(entity.getId());
        Preconditions.checkNotNull(before, "待更新的用户不存在");
        SysUser after = SysUser.builder()
                .id(entity.getId())
                .username(entity.getUsername())
                .telephone(entity.getTelephone())
                .mail(entity.getMail())
                .deptId(entity.getDeptId())
                .status(entity.getStatus())
                .remark(entity.getRemark()).build();
//        after.setOperator(RequestHolder.getCurrentUser().getUsername());
//        after.setOperatorIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
//        after.setOperatorTime(new Date());
        setOpratorInfo(after);
        sysUserMapper.updateByPrimaryKeySelective(after);
        //sysLogService.saveUserLog(before, after);
    }

    @Override
    public void delete(int id) {

    }


    public boolean checkEmailExist(String mail, Integer userId) {
        return sysUserMapper.countByMail(mail, userId) > 0;
    }

    public boolean checkTelephoneExist(String telephone, Integer userId) {
        return sysUserMapper.countByTelephone(telephone, userId) > 0;
    }


    public SysUser findByKeyword(String keyword) {
            return sysUserMapper.findByKeyword(keyword);
    }

    public PageResult<SysUser> getPageByDeptId(Integer deptId, PageQuery page) {
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }
}
